package com.ruoyi.web.controller.workJob;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelHandleUtil;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.worker.domain.CycleSchedule;
import com.ruoyi.worker.domain.TermSchedule;
import com.ruoyi.worker.domain.TermTimeShift;
import com.ruoyi.worker.domain.UserSchedule;
import com.ruoyi.worker.service.TermScheduleService;
import com.ruoyi.worker.service.TermTimeShiftService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: TermScheduleController
 * @Description:
 * @Author: 刘松山
 * @Date: 2021/10/14 20:44
 */
@RestController
@RequestMapping("/workJobApi/termSchedule")
public class TermScheduleController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(TermScheduleController.class);
    @Autowired
    private TermScheduleService termScheduleService;
    @Autowired
    private TermTimeShiftService termTimeShiftService;
    @Autowired
    private ISysRoleService iSysRoleService;

    // @PreAuthorize("@ss.hasPermi('job:attendanceGroup:list')")
    @GetMapping("/listTermSchedule")
    public TableDataInfo listTermSchedule(TermSchedule termSchedule) {
        startPage();
        List<TermSchedule> list = termScheduleService.listTermSchedule(termSchedule);
        return getDataTable(list);
    }

    /**
     * 获取考勤组下需要排班的用户
     *
     * @return com.ruoyi.common.core.page.TableDataInfo
     * @author 刘松山
     * @date 2021/10/16 10:39
     */
    @GetMapping("/listUserSchedule")
    public TableDataInfo listUserSchedule(@RequestParam Map<String, Object> map) {

        List<Map<String, Object>> list = termScheduleService.listUserSchedule(map);
        return getDataTable(list);
    }

    @GetMapping("/listRole")
    public TableDataInfo listRole() {
        SysRole sysRole = new SysRole();
        List<SysRole> list = iSysRoleService.selectRoleList(sysRole);
        return getDataTable(list);
    }

    @GetMapping("/listTermTimeShift")
    public TableDataInfo listTermTimeShift(TermTimeShift termTimeShift) {
        termTimeShift.setStatus(0);
        List<TermTimeShift> list = termTimeShiftService.listTermTimeShift(termTimeShift);

        for (TermTimeShift t : list) {
            String showTime = "";
            String showTimeOther = "";
            if (t.getType() == 0) {
                showTime = t.getName();
                showTimeOther = "";

            } else if (t.getType() == 1) {
                showTime = t.getName() + " " + t.getFirstBeginTime() + "-" + t.getFirstEndTime();
                showTimeOther = t.getFirstBeginTime() + "-" + t.getFirstEndTime();

            } else if (t.getType() == 2) {
                showTime = t.getName() + " " + t.getFirstBeginTime() + "-" + t.getFirstEndTime()
                        + "  " + t.getSecondBeginTime() + "-" + t.getSecondEndTime();
                showTimeOther = t.getFirstBeginTime() + "-" + t.getFirstEndTime()
                        + "  " + t.getSecondBeginTime() + "-" + t.getSecondEndTime();

            } else if (t.getType() == 3) {
                showTime = t.getName() + " " + t.getFirstBeginTime() + "-" + t.getFirstEndTime()
                        + "  " + t.getSecondBeginTime() + "-" + t.getSecondEndTime()
                        + "  " + t.getThreeBeginTime() + "-" + t.getThreeEndTime();
                showTimeOther = t.getFirstBeginTime() + "-" + t.getFirstEndTime()
                        + "  " + t.getSecondBeginTime() + "-" + t.getSecondEndTime()
                        + "  " + t.getThreeBeginTime() + "-" + t.getThreeEndTime();


            } else if (t.getType() == 4) {
                showTime = t.getName() + " " + t.getFirstBeginTime() + "-" + t.getFirstEndTime()
                        + "  " + t.getSecondBeginTime() + "-" + t.getSecondEndTime()
                        + "  " + t.getThreeBeginTime() + "-" + t.getThreeEndTime()
                        + "  " + t.getFourBeginTime() + "-" + t.getFourEndTime();
                showTimeOther = t.getFirstBeginTime() + "-" + t.getFirstEndTime()
                        + "  " + t.getSecondBeginTime() + "-" + t.getSecondEndTime()
                        + "  " + t.getThreeBeginTime() + "-" + t.getThreeEndTime()
                        + "  " + t.getFourBeginTime() + "-" + t.getFourEndTime();
            }


            t.setShowDateTime(showTime);
            t.setShowDateTimeOther(showTimeOther);
        }
        return getDataTable(list);
    }

    @GetMapping("/listCycleSchedule")
    public TableDataInfo listCycleSchedule() {
        List<CycleSchedule> list = termScheduleService.listCycleSchedule();
        for (CycleSchedule t : list) {
            String showTime = "";
            if (t.getType() == 1) {
                showTime = t.getName() + " " + t.getFirstBeginTime() + "-" + t.getFirstEndTime();


            } else if (t.getType() == 2) {
                showTime = t.getName() + " " + t.getFirstBeginTime() + "-" + t.getFirstEndTime()
                        + "  " + t.getSecondBeginTime() + "-" + t.getSecondEndTime();


            } else if (t.getType() == 3) {
                showTime = t.getName() + " " + t.getFirstBeginTime() + "-" + t.getFirstEndTime()
                        + "  " + t.getSecondBeginTime() + "-" + t.getSecondEndTime()
                        + "  " + t.getThreeBeginTime() + "-" + t.getThreeEndTime();


            } else if (t.getType() == 4) {
                showTime = t.getName() + " " + t.getFirstBeginTime() + "-" + t.getFirstEndTime()
                        + "  " + t.getSecondBeginTime() + "-" + t.getSecondEndTime()
                        + "  " + t.getThreeBeginTime() + "-" + t.getThreeEndTime()
                        + "  " + t.getFourBeginTime() + "-" + t.getFourEndTime();

            }

            t.setShowDateTime(showTime);

        }
        return getDataTable(list);
    }


    //@PreAuthorize("@ss.hasPermi('job:attendanceGroup:query')")
    @GetMapping(value = {"/", "/{id}"})
    public AjaxResult getTermSchedule(@PathVariable(value = "id", required = false) Long id) {
        AjaxResult ajax = AjaxResult.success();

        if (StringUtils.isNotNull(id)) {
            ajax.put(AjaxResult.DATA_TAG, termScheduleService.getTermSchedule(id));

        }
        return ajax;
    }

    //  @PreAuthorize("@ss.hasPermi('workJobApi:attendance:add')")
    @Log(title = "新增", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult addTermSchedule(@Validated @RequestBody TermSchedule termSchedule) {
        List<UserSchedule> userDateScheduleList = termScheduleService.listuserDateSchedule(termSchedule);
        if (userDateScheduleList.size() > 0) {
            String msg = "";
            for (UserSchedule u : userDateScheduleList) {
                msg = msg + "用户：" + u.getUserName() + "日期：" + "已经排班了 ";
            }
            return AjaxResult.error("不能新增排班" + msg + " 请核对！");
        }
        termSchedule.setCreateBy(getUsername());
        int flag = termScheduleService.addTermSchedule(termSchedule);
//        if (flag < 0) {
//            return AjaxResult.error(termSchedule.getName() + "的班次已经存在了");
//        }
        return toAjax(flag);
    }


    //  @PreAuthorize("@ss.hasPermi('workJobApi:attendance:add')")
    @Log(title = "新增周期排班", businessType = BusinessType.INSERT)
    @PostMapping("/addCycleSchedule")
    public AjaxResult addCycleSchedule(@Validated @RequestBody List<CycleSchedule> list) {

        for (CycleSchedule c : list) {
            c.setCreateBy(getUsername());
        }

        int flag = termScheduleService.addCycleSchedule(list);

        return toAjax(flag);
    }

    @Log(title = "修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody TermSchedule termSchedule) {

        termSchedule.setUpdateBy(getUsername());
        int flag = termScheduleService.modifyTermSchedule(termSchedule);
//        if (flag < 0) {
//            return AjaxResult.error(termSchedule.getName() + "的班次已经存在了");
//        }
        return toAjax(flag);
    }

    @Log(title = "修改状态", businessType = BusinessType.UPDATE)
    @PostMapping("/editStatus")
    public AjaxResult editStatus(@Validated @RequestBody TermSchedule termSchedule) {

        termSchedule.setUpdateBy(getUsername());
        int flag = termScheduleService.modifyTermScheduleStatus(termSchedule);

        return toAjax(flag);
    }

    /**
     * 删除
     */
    //@PreAuthorize("@ss.hasPermi('job:attendanceGroup:detail:delete')")
    @Log(title = "删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult delBacthTermSchedule(@PathVariable Long[] ids) {
        return toAjax(termScheduleService.delBacthTermSchedule(ids));
    }

    @GetMapping("/userScheduleExport")
    public AjaxResult userScheduleExport(String id, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        TermSchedule t = termScheduleService.getTermSchedule(Long.parseLong(id));
        if (param.get("beginTime") == null) {
            param.put("beginTime", t.getBeginTime());
            param.put("endTime", t.getEndTime());
        }
        List<Map<String, Object>> list = termScheduleService.listUserSchedule(param);
        if (list.isEmpty()) {
            return AjaxResult.error("需要导出的数据为空");
        }
        OutputStream output = null;
        try {

            List<String> titleList = new ArrayList<>();
            List<String> filedNames = new ArrayList<>();
            titleList.add("用户名称");
            titleList.add("岗位");
            filedNames.add("userName");
            filedNames.add("postName");

            List<String> dataList = DateUtils.findDates(t.getBeginTime(), t.getEndTime());
            for (int i = 0; i < dataList.size(); i++) {

                titleList.add(dataList.get(i));
                filedNames.add(dataList.get(i));
            }
//            List<String> titleList = Arrays.asList(title);
//            List<String> filedNames = Arrays.asList(name);
            output = response.getOutputStream();
            response.reset();
            response.setHeader("Content-disposition", "attachment; filename=" + System.currentTimeMillis() + "_schedule.xls");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            HSSFWorkbook workbook = ExcelHandleUtil.exportExcel(titleList, list, filedNames);
            workbook.write(output);
            return AjaxResult.success("导出成功，请查看");
        } catch (Exception e) {
            logger.debug("导出失败：" + e.getMessage());
            return AjaxResult.error("导出失败");
        } finally {
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

    @PostMapping("/importSchedule/{dateTime}")
    public AjaxResult importSchedule(MultipartFile[] file, @PathVariable String dateTime) {
        //获取排班日期
        String[] timeArray = null;
        List<String> dateList = null;
        if (dateTime == null || "".equals(dateTime)) {
            return AjaxResult.error("排班时间为空，请核对");
        } else {
            timeArray = dateTime.split("&");

            try {
                dateList = DateUtils.findDates(timeArray[0], timeArray[1]);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        Map<String, Object> param = new HashMap<>();
        if (timeArray[2] == null || "".equals(timeArray[2])) {
            return AjaxResult.error("分组为空，请核对");
        }


        param.put("groupId", timeArray[2]);
        List<Map<String, Object>> userList = this.termScheduleService.listUserScheduleList(param);
        //返回页面的的list集合
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        Workbook wb = null;
        try {
            if (file != null) {
                MultipartFile f = file[0];
                InputStream in = f.getInputStream();
                String fileName = f.getOriginalFilename();
                if (fileName != null && fileName.endsWith(".xlsx")) {
                    wb = new XSSFWorkbook(in);
                } else if (fileName != null && fileName.endsWith(".xls")) {
                    wb = new HSSFWorkbook(in);
                } else {
                    throw new Exception("文件格式不正确，不能导入！");
                }
                // 打开HSSFWorkbook
                Row row = null;
                Map<String, Object> rowMap = null;


                Sheet st = wb.getSheetAt(0);

                row = st.getRow(0);
                if (row.getLastCellNum() < dateList.size() + 3) {
                    return AjaxResult.error("导入的excel表格内容中排班日期和实际选择的不符合，请核对");
                }
                for (int i = 0; i < dateList.size(); i++) {
                    if (!dateList.get(i).equals(ExcelHandleUtil.getCellValue(row.getCell(i + 3)) + "")) {
                        return AjaxResult.error("excel表格内容中排班日期:" + ExcelHandleUtil.getCellValue(row.getCell(i + 3))
                                + "和实际选择的" + dateList.get(i) + "不符合，请核对");
                    }
                }

                //循环行
                for (int rowIndex = 1; rowIndex <= st.getLastRowNum(); rowIndex++) {

                    row = st.getRow(rowIndex);

                    rowMap = new HashMap<String, Object>();

                    if (ExcelHandleUtil.getCellValue(row.getCell(1)) == null) {
                        return AjaxResult.error("第" + (rowIndex + Integer.parseInt("1")) + "行身份证为空，请核对");
                    } else {
                        rowMap.put("idCard", ExcelHandleUtil.getCellValue(row.getCell(1)));
                    }

                    for (int i = 0; i < dateList.size(); i++) {
                        if (ExcelHandleUtil.getCellValue(row.getCell(i + 3)) == null) {
                            return AjaxResult.error("第" + (rowIndex + Integer.parseInt("1")) + "行排班为空，请核对");
                        } else {
                            rowMap.put(dateList.get(i), ExcelHandleUtil.getCellValue(row.getCell(i + 3)));
                        }
                    }

                    if (ExcelHandleUtil.getCellValue(row.getCell(0)) == null) {
                        return AjaxResult.error("第" + (rowIndex + Integer.parseInt("1")) + "行长期工名称为空，请核对");
                    } else {
                        int flag = 0;
                        //后面用长期工姓名+身份证校验 获取长期工id
                        for (int i = 0; i < userList.size(); i++) {
                            if ((ExcelHandleUtil.getCellValue(row.getCell(0)) + "").equals(userList.get(i).get("userName") + "")) {
                                rowMap.put("userName", ExcelHandleUtil.getCellValue(row.getCell(0)));
                                rowMap.put("userId", userList.get(i).get("userId"));
                                rowMap.put("postName", ExcelHandleUtil.getCellValue(row.getCell(2)));
                                rowMap.put("postId", userList.get(i).get("postId"));
                                userList.remove(i);
                                flag = 1;
                                break;
                            }
                        }
                        if (flag == 0) {
                            return AjaxResult.error("第" + (rowIndex + Integer.parseInt("1")) + "行长期工:" + ExcelHandleUtil.getCellValue(row.getCell(0)) + "不在当前考勤组下，请核对");
                        }

                    }

                    resultList.add(rowMap);

                }

            }
        } catch (Exception e) {
            logger.debug("导入失败!" + e.getMessage());
            return AjaxResult.error("导入失败");

        } finally {
            try {
                if (wb != null) {
                    wb.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return AjaxResult.success(resultList);
    }
}
